<?php

namespace PhpSeverless\Adapter;

use PhpSeverless\CgiResponseParser;
use PhpSeverless\Request;

class Tencent implements AdapterInterface
{
    public function handleResponse(string $raw)
    {
        $parser = new CgiResponseParser($raw);

        $headers = $parser->getHeaders();
        $body = $parser->getBody();
        $statusCode = $parser->getStatusCode();

        return array(
            'isBase64Encoded' => true,
            'statusCode'      => $statusCode,
            'headers'         => $headers,
            'body'            => base64_encode($body),
        );
    }

    public function pathscript(string $path)
    {
        preg_match('/(.*)\.php\/|(.*)\.php$/', $path, $res);

        $script = $res[0] ?? '/index.php';
        if (substr($script, -1) == '/') {
            $script = substr($script, 0, -1);
        }

        return $script;
    }

    public function handleRequest(array $param):  ? Request
    {
        $event = $param['event'];

        $query = http_build_query(json_decode(json_encode($event->queryString ?? []), true));
        $body = $event->isBase64Encoded ? base64_decode($event->body) : $event->body;
        $headers = json_decode(json_encode($event->headers ?? []), true);
        $path = $event->path;
        $uri = $event->path . (!empty($query) ? '?' . $query : '');
        $method = $event->httpMethod;
        $remote_addr = $event->requestContext->sourceIp;
        $script = $this->pathscript($path);

        $request = new Request();
        $request->headers = $headers;
        $request->scheme = 'http';
        $request->script = $script;
        $request->method = $method;
        $request->remote_addr = $remote_addr;
        $request->query_string = $query;
        $request->request_uri = $uri;
        $request->body = $body;
        $request->pathinfo = str_replace($script, '', $path);

        return $request;
    }
}
